package cn.hd01.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.hd01.repository.HotRecommendRepository;
import cn.hd01.repository.entity.HotRecommend;
import cn.hd01.service.HotRecommendService;
@Service
public class HotRecommendServiceImpl extends BaseServiceImpl<HotRecommend, Integer> implements HotRecommendService {

	private HotRecommendRepository repository;
	
	@Autowired
	public HotRecommendServiceImpl(HotRecommendRepository repository) {
		super(repository);
		this.repository = repository;
	}

	@Override
	public Page<HotRecommend> findAll(final HotRecommend hotRecommend, Pageable pageable) {
		if (hotRecommend == null) {
			return repository.findAll(pageable);
		}

		return repository.findAll(Specifications.where(new Specification<HotRecommend>() {
			@Override
			public Predicate toPredicate(Root<HotRecommend> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<Predicate>();

				if (StringUtils.hasText(hotRecommend.getName())) {
					predicates.add(cb.like(r.get("name").as(String.class), "%" + hotRecommend.getName() + "%"));
				}
				
				return cb.and(predicates.toArray(new Predicate[] {}));
			}
		}), pageable);
		
	}

	@Override
	public int updateHotRecommend(String name, String url, String image, Integer id) {
		return repository.updateHotRecommend(name, url, image, id);
	}
}
